<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区域 -->
    <div style="margin-top: 15px;">
      <el-input
        v-model="query"
        style="width:300px;margin-right:15px"
        placeholder="请输入内容"
        class="input-with-select"
        @keyup.enter.native="suaix"
      >
        <el-button slot="append" icon="el-icon-search" @click="suaix"></el-button>
      </el-input>
      <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
    </div>
    <br />
    <!-- 表格区域 -->
    <el-table :data="userList" border style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-model="scope.row.mg_state"
            @change="upSwitch(scope.row.id,scope.row.mg_state)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click='editShow(scope.row)'></el-button>
          <el-button type="primary" icon="el-icon-share" @click="granShow(scope.row)"></el-button>
          <el-button type="primary" icon="el-icon-delete" @click="delusers(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" :model="addForm" :label-width="'80px'" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="userRole">
      <el-form :model="granform" :label-width="'120px'">
        <el-form-item label="用户名">
          <el-input
            v-model="granform.name"
            auto-complete="off"
            :disabled="true"
            style="width:100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="granform.rid" clearable placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userRole = false">取 消</el-button>
        <el-button type="primary" @click="getUserRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editUsers">
      <el-form :rules="rules" :model="editForm" :label-width="'80px'" ref="editForm">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editForm.username" auto-complete="off" disabled="disabled" style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUsers = false">取 消</el-button>
        <el-button type="primary" @click="editUserf">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  addForm,
  delUser,
  upDataUserState,
  grantUserRole,
  editUser
} from '@/api/user_api.js'
import { getAllRoleLlist } from '@/api/role.js'
export default {
  data () {
    return {
      // 添加用户
      addForm: {
        username: '',
        password: '',
        email: 'a@b.com',
        mobile: '13456789098'
      },
      // 添加用户规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 50, message: '密码请设置6位数以上', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
            pattern: /\w+[@]\w+[.]\w{2,3}/
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入11位电话号码',
            trigger: 'blur',
            pattern: /^1[345678]\d{9}$/
          }
        ]
      },
      // 编辑用户
      editUsers: false,
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户角色模态框
      value4: '',
      userRole: false,
      roleOptions: [],
      granform: {
        name: '',
        rid: '',
        id: ''
      },
      // 添加用户模态框
      dialogFormVisible: false,
      total: 0,
      // 用于用户筛选查询
      query: '',
      // 当前页码
      pagenum: 1,
      pagesize: 4,
      userList: []
    }
  },
  mounted () {
    // 获取页面数据
    this.init()
    // 获取所有角色列表数据
    getAllRoleLlist()
      .then(res => {
        if (res.data.meta.status === 200) {
          this.roleOptions = res.data.data
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  methods: {
    // 编辑用户信息
    editUserf () {
      // 还要再次判断用户是否编辑信息没有空值
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          editUser(this.editForm)
            .then((res) => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.editUsers = false
                this.init()
              } else {
                this.$message({
                  type: 'error',
                  message: '输入的信息不合法'
                })
              }
            }).catch((err) => {
              console.log(err)
            })
        }
      })
    },
    // 显示编辑用户对话框
    editShow (row) {
      this.editUsers = true
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    // 修改用户信息分配角色
    getUserRole () {
      if (!this.granform.rid) {
        this.$message({
          type: 'error',
          message: '请选择角色!'
        })
        return false
      }
      grantUserRole(this.granform.id, this.granform.rid)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message({
              type: 'success',
              message: res.data.meta.msg
            })
            this.userRole = false
            this.init()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 显示修改用户信息窗口
    granShow (row) {
      this.userRole = true
      this.granform.id = row.id
      this.granform.rid = row.rid
      this.granform.name = row.username
    },
    // 修改用户状态
    upSwitch (id, type) {
      console.log(id)
      upDataUserState(id, type)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 删除用户
    delusers (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUser(id)
            .then(res => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.pagenum =
                  Math.ceil(this.total - 1 / this.pagesize) < this.pagenum
                    ? --this.pagenum
                    : this.pagenum
                this.init()
              }
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '删除失败!'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取用户数据
    init () {
      getUserList({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
        .then(res => {
          // console.log(res)
          this.userList = res.data.data.users
          this.total = res.data.data.total
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 用户筛选
    suaix () {
      this.pagenum = 1
      this.init()
    },
    // 分页设置
    handleSizeChange (val) {
      this.pagesize = val
      this.init()
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.init()
    },
    // 添加用户
    addUser () {
      // 数据验证是否符合格式
      this.$refs.addForm.validate(valid => {
        if (valid) {
          addForm(this.addForm)
            .then(res => {
              console.log(res)
              if (res.data.meta.status === 201) {
                // 隐藏模态框
                this.dialogFormVisible = false
                // 清空表单
                this.$refs.addForm.resetFields()
                // 重新渲染页面
                this.init()
              } else {
                this.$message({
                  message: res.data.meta.msg,
                  type: 'error'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
